﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using XUCore.Extensions;
using XUCore.Serializer;
using XUCore.Serializer.Converters;

namespace XUCore.NetCore.RestFul
{
    internal static class Utils
    {
        public static void FormatterJsonOptions(HttpContext context, FormatterOptions options)
        {
            if (options.JsonSerializerSettings != null && options.JsonSerializerSettings.ContractResolver?.GetType() == typeof(LimitPropsContractResolver))
            {
                var headers = context.Request.Headers;
                // col1,col2
                var fields = headers["limit-field"].SafeString().Split(",", true);
                // 指定输出字段 contain or match or equal
                // 忽略指定字段 ignore
                var limitMode = headers["limit-mode"].SafeString().ToLower();
                // 解析器 camelcase 小驼峰 ， default 默认大写
                var contractResolverMode = headers["limit-resolver"].SafeString().ToLower();
                // column1=col1,column2=col2
                var rename = headers["limit-field-rename"].SafeString().ToMap(',', '=', true, false, true);

                var dateFormat = Web.UrlDecode(headers["limit-date-format"].SafeString());
                var dateUnix = headers["limit-date-unix"].SafeString().ToLower();

                options.JsonSerializerSettings.DateFormatString = dateFormat.NotEmpty() ? dateFormat : string.Empty;

                options.JsonSerializerSettings.Converters.Clear();

                if (dateUnix.NotEmpty() && dateUnix.Equals("true"))
                {
                    options.JsonSerializerSettings.Converters.Add(new DateTimeToUnixConverter());
                    options.JsonSerializerSettings.Converters.Add(new DateTimeNullToUnixConverter());
                }

                if (context.Request.Query.ContainsKey("indented"))
                    options.JsonSerializerSettings.Formatting = context.Request.Query("indented", false) ? Formatting.Indented : Formatting.None;

                var _limitType = limitMode switch
                {
                    "contain" or "match" or "equal" => LimitPropsMode.Contains,
                    _ => LimitPropsMode.Ignore,
                };

                var _resolverMode = contractResolverMode switch
                {
                    "camelcase" => ResolverMode.CamelCase,
                    "default" => ResolverMode.Default,
                    _ => options.ResolverDefault,
                };

                options.JsonSerializerSettings.ContractResolver = new LimitPropsContractResolver(fields, _limitType, rename, _resolverMode);
            }
        }
    }
}
